<template>
  <div class="portal-share-wrap">
    <!-- h5海报 -->
    <div class="portal-share-container">
      <div class="portal-share-container-header">
        <span class="portal-share-container-header-desc">h5</span>
        <el-button type="text" @click="downloadHandelClick(1)">{{ $t('portal.saveAndDownload') }}</el-button>
      </div>
      <div
        ref="poster"
        id="poster"
        class="share-poster"
        :class="{ 'share-poster-hide': type !== 1 }"
      >
        <img
          v-if="shareConfig.sharePicture"
          :src="shareConfig.sharePicture"
          alt=""
        />
        <div v-else class="no-image">
          <i class="iconfont icon-image-fill"></i>
          <span>{{ $t('common.base.image') }}</span>
        </div>

        <div class="share-poster-text">
          <h3>{{ shareConfig.shareTitle | ellipsis(15, true) }}</h3>
          <span>{{ shareConfig.shareDescribe }}</span>
        </div>
        <div class="share-poster-qrCode">
          <div id="qrcode" ref="qrcode"></div>
          <span>{{ $t('portal.posterTip5') }}</span>
        </div>
      </div>

      <!-- 微信朋友 -->
      <div class="share-weChat_friend" v-if="type === 2" :style="wechatFriendImage">
        <div class="share-weChat_friend-content">
          <div>
            <h3>{{ shareConfig.shareTitle }}</h3>
            <h4>{{ shareConfig.shareDescribe }}</h4>
          </div>
          <img
            v-if="shareConfig.sharePicture"
            :src="shareConfig.sharePicture"
            alt=""
          />
        </div>
      </div>

      <!-- 微信朋友圈 -->
      <div class="share-weChat_Moments" v-if="type === 3" :sytle="wechatMomentImage">
        <div class="share-weChat_Moments-content">
          <img
            v-if="shareConfig.sharePicture"
            :src="shareConfig.sharePicture"
            alt=""
          />
          <h3>{{ shareConfig.shareTitle | ellipsis(14, true) }}</h3>
        </div>
      </div>
    </div>
    <!-- 小程序海报 -->
    <div v-if="appletCodeUrl" class="portal-share-container mar-l-24">
      <div class="portal-share-container-header">
        <span class="portal-share-container-header-desc">{{ $t('common.base.applet') }}</span>
        <el-button type="text" @click="downloadHandelClick(2)">{{ $t('portal.saveAndDownload') }}</el-button>
      </div>
      <div
        class="share-poster"
        :class="{ 'share-poster-hide': type !== 1 }"
      >
        <img
          v-if="shareConfig.sharePicture"
          :src="shareConfig.sharePicture"
          alt=""
        />
        <div v-else class="no-image">
          <i class="iconfont icon-image-fill"></i>
          <span>{{ $t('common.base.image') }}</span>
        </div>
      
        <div class="share-poster-text">
          <h3>{{ shareConfig.shareTitle | ellipsis(15, true) }}</h3>
          <span>{{ shareConfig.shareDescribe }}</span>
        </div>
        <div class="share-poster-qrCode">
          <img class="share-poster-qrCode-miniImg" :src="appletCodeUrl" alt="">
          <span>{{ $t('portal.posterTip5') }}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, nextTick, onBeforeMount } from 'vue';
import QRCode from 'qrcodejs2';
import { downloadDoorPosterV2, downloadDoorAppletCodePoster } from '@src/api/PortalApi.ts';
import html2canvas from 'html2canvas';
import { getLocalesOssUrl } from '@src/util/assets'
const wechatFriendImage = `background-image: url(${getLocalesOssUrl('/weChatFriend.png')});`
const wechatMomentImage = `background-image: url(${getLocalesOssUrl('/weChatMoments.png')});`
import i18n from '@src/locales';
export default {
  props: {
    config: {
      type: Object,
      default: () => ({}),
    },
    link: {
      type: String,
      default: '',
    },
    type: {
      type: Number,
      default: 1,
    },
    doorTypeId: {
      type: Number,
    },
    appletCodeUrl: {
      type: String,
      default: '',
    },
  },
  setup(props, { emit }) {
    const shareConfig = computed(() => {
      return props.config;
    });

    const qrcode = ref(null);
    const poster = ref(null);
    const downloadType = ref('');
    const getQrcode = () => {
      new QRCode('qrcode', {
        width: 78,
        height: 78,
        text: props.link,
        colorDark: '#000000',
        colorLight: '#ffffff',
        correctLevel: QRCode.CorrectLevel.H,
      });
    };

    const downloadQrcode = () => {
      let domCanvas = qrcode.value;
      let width = domCanvas.scrollWidth;
      let height = domCanvas.scrollHeight;
      let scale = 2;
      html2canvas(domCanvas, {
        scale, // 放大倍数
        width,
        height,
        useCORS: true, // 开启跨域配置
      })
        .then((canvas) => {
          let a = document.createElement('a');
          let event = new MouseEvent('click');
          a.href = canvas.toDataURL('image/png');
          a.download = i18n.t('portal.posterQRCode');
          a.dispatchEvent(event);
        })
        .catch((err) => {
          console.log('downloadQrcode error', err);
        });
    };
    
    // base64转blob
    const base64ToBlob = (code) => { 
      let parts = code.split(';base64,');
      let contentType = parts[0].split(':')[1];
      let raw = window.atob(parts[1]);
      let ranLength = raw.length;

      let uint8Array = new Uint8Array(ranLength);

      for (let i = 0; i < ranLength; ++i) {
        uint8Array[i] = raw.charCodeAt(i);
      }

      return new Blob([uint8Array], {type: contentType})
    }
    const  downloadMiniPoster = async ()=> {
      try {
        const params = { 
          appletCodeUrl: props.appletCodeUrl,
          typeId:props.doorTypeId
        }
        const { code } = await downloadDoorAppletCodePoster(params);
        if (!code) return;
        
        let a = document.createElement('a');
        let event = new MouseEvent('click');
        const blob = base64ToBlob(code)
        const blobUrl = window.URL.createObjectURL(blob);

        a.href = blobUrl;
        a.setAttribute('download', `${i18n.t('portal.portalPoster')}.png`)
        a.dispatchEvent(event);

      } catch (error) {
        console.error('downloadPoster error', error);
      }
    }

    const downloadH5Poster = async () => {
      try {
        const params = { 
          codePath: props.link,
          typeId:props.doorTypeId
        }
        const { code } = await downloadDoorPosterV2(params);
        if (!code) return;
        
        let a = document.createElement('a');
        let event = new MouseEvent('click');
        const blob = base64ToBlob(code)
        const blobUrl = window.URL.createObjectURL(blob);

        a.href = blobUrl;
        a.setAttribute('download', `${i18n.t('portal.portalPoster')}.png`)
        a.dispatchEvent(event);

      } catch (error) {
        console.error('downloadPoster error', error);
      }
    };

    const downloadPoster = async () => {
      const type = downloadType.value;
      if (type == 1) {
        downloadH5Poster();
      } else if (type == 2) {
        downloadMiniPoster();
      }
    };

    function downloadHandelClick(type) {
      // type 1: h5 2: 小程序 
      downloadType.value = type;
      emit('saveDownload')
    };

    onBeforeMount(() => {
      nextTick(() => {
        getQrcode();
      })
    })

    return {
      shareConfig,
      qrcode,
      poster,
      downloadQrcode,
      downloadPoster,
      wechatMomentImage,
      wechatFriendImage,
      downloadHandelClick,
    };
  },
  filters: {
    ellipsis(value, num, flag = false) {
      if (!value) return;

      if (flag) return value.substring(0, num);

      return `${value.substring(0, num)}...`;
    },
  },
};
</script>

<style lang="scss" scoped>
@import "../index";
.portal-share-wrap {
  display: flex;
}
.portal-share-container {
  width: 258px;
  height: 100%;
  &-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0px 0;
    &-desc {
      font-size: 14px;
      color: #262626;
    }
  }
  .share-poster {
    width: 100%;
    height: 100%;
    background: #ffffff;
    border: 1px solid #d9d9d9;
    display: flex;
    flex-direction: column;
    img {
      width: 100%;
      height: 207px;
    }

    .no-image {
      width: 100%;
      height: 207px;
      background: #f5f5f5;
      border-radius: 4px 4px 0px 0px;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;

      i {
        font-size: 28px;
        color: #bfbfbf;
        margin-bottom: 14px;
      }

      span {
        font-size: 14px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #595959;
        line-height: 22px;
      }
    }

    .share-poster-text {
      display: flex;
      flex-direction: column;
      align-items: center;
      margin-bottom: 20px;
      margin-top: 20px;

      h3 {
        @include font-setting(14px, 500, #262626, 22px);
        margin-bottom: 6px;
      }

      span {
        @include font-setting(13px, 400, #bfbfbf, 22px);
        margin: 0 30px;
      }
    }

    .share-poster-qrCode {
      display: flex;
      flex-direction: column;
      align-items: center;
      margin-bottom: 12px;

      span {
        margin-top: 6px;
        @include font-setting(12px, 400, #8c8c8c, 20px);
      }

      &-miniImg {
        width: 78px;
        height: 78px;
      }
    }
  }

  .share-poster-hide {
    position: absolute;
    z-index: -999;
    width: 260px;
    height: 440px;
  }

  .share-weChat_friend {
    width: 100%;
    height: 100%;
    background-repeat:'no-repeat';
    background-size: 100% 100%;
    position: relative;

    .share-weChat_friend-content {
      min-height: 40px;
      @include box-setting(180px, auto, #ffffff);
      position: absolute;
      top: 104px;
      right: 42px;
      display: flex;
      align-items: flex-end;
      padding: 0 2px 0 6px;

      div {
        width: calc(100% - 36px);

        h3 {
          @include font-setting(12px, 500, #262626, 16px);
          margin: 5px 0;
        }

        h4 {
          @include font-setting(13px, 400, #bfbfbf, 14px);
          margin-bottom: 5px;
          -webkit-transform-origin-x: 0;
          -webkit-transform: scale(0.8);
        }
      }

      img {
        @include box-setting(30px, 30px, #ffffff, 50%);
        margin-bottom: 10px;
      }
    }

    .share-weChat_friend-content::before {
      content: "";
      display: block;
      position: absolute;
      width: 0;
      height: 0;
      border: 4px solid transparent;
      border-left-color: #fff;
      left: 180px;
      top: 10px;
    }
  }

  .share-weChat_Moments {
    width: 100%;
    height: 100%;
    background-repeat:'no-repeat';
    background-size: 100% 100%;
    position: relative;

    .share-weChat_Moments-content {
      position: absolute;
      top: 303px;
      left: 46px;
      display: flex;
      align-items: center;

      img {
        width: 30px;
        height: 30px;
      }

      h3 {
        @include font-setting(13px, 500, #262626, 22px);
        margin: 0 0 0 2px;
        -webkit-transform-origin-x: 0;
        -webkit-transform: scale(0.8);
      }
    }
  }
}
</style>
